package com.dmy.chat.server.netty.command;

import com.dmy.chat.server.netty.UserChannelBind;
import com.dmy.chat.server.netty.message.Messages;
import com.dmy.common.context.ApplicationContextHolder;
import com.dmy.mapper.MsgContentInfoMapper;
import com.dmy.model.MsgContentList;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * create by YCQ for 2020/1/15 14:57
 */
public class UserChatCommand extends AbstractUserEventCommand{
    public UserChatCommand(UserChannelBind channelBind, Channel channel, Messages messages) {
        super(channelBind, channel, messages);
        contentInfoMapper = ApplicationContextHolder.get().getBean(MsgContentInfoMapper.class);
    }
    private MsgContentInfoMapper contentInfoMapper;


    @Override
    public void exec0() {
        /*
            1.接收消息并推送
            2.消息存入数据库中
            3.消息签收
            4.心跳机制
         */
        String content = messages.getContent();
        String sender = messages.getSender();
        String receive = messages.getReceive();
        Date date = new Date();

        // 给发送者响应已经处理成功
        channel.writeAndFlush(new TextWebSocketFrame(ENCODER.encode(messages)));

        // 接收方channel
        Channel cha = channelBind.getUserChannel(receive);

        // 保存消息到数据库
        MsgContentList contentList = new MsgContentList();
        contentList.setContent(messages.getContent());
        contentList.setMsgType(2);
        contentList.setReceiveId(messages.getReceive());
        contentList.setSenderId(messages.getSender());
        contentList.setShowFlag(0);
        contentList.setCreateTime(new Date());
        contentList.setDel(1);
        contentList.setUpdateTime(new Date());
        contentInfoMapper.insert(contentList);

        // 给接受者推送消息
        if(!ObjectUtils.isEmpty(cha)){
            Messages msg = new Messages();
            msg.setContent(content);
            msg.setCmd(EventType.CHAT_FRIEND.getType());
            msg.setDate(new Date());
            msg.setReceive(receive);
            msg.setSender(sender);
            msg.setMsgType(messages.getMsgType());
            msg.setMsgId(contentList.getId());

            cha.writeAndFlush(new TextWebSocketFrame(ENCODER.encode(msg)));
        }
    }
}
